import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_author.dart';
import 'package:osc/models/entity/osc_favorite_reverse_result_entity.dart';
import 'package:osc/models/entity/osc_post_detail_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/comment/comment_list.dart';
import 'package:osc/ui/pages/common_page.dart';
import 'package:osc/ui/widgets/comment/project_comment_bar_widget.dart';
import 'package:osc/ui/widgets/comment/project_comment_input_widget.dart';
import 'package:osc/ui/widgets/common_scaffold.dart';
import 'package:osc/ui/widgets/real_rich_text.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/user/osc_author_widget.dart';
import 'package:osc/ui/widgets/web_widget.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/string_util.dart';
import 'package:osc/utils/time_util.dart';

///帖子
class PostDetailPage extends StatefulWidget {
  final int id;
  final int type;
  const PostDetailPage({Key key, @required this.id, @required this.type}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new PostDetailPageState(id, type);
  }
}

class PostDetailPageState extends State<PostDetailPage> {
  final int id;
  final int type;
  PostDetailPageState(this.id, this.type);

  HttpRepository httpRepository;
  bool isLoadedData = false;


  double paddingChildVertical = Dimens.gap_view_normal;

  OscPostDetailEntity detail;
  OscPostExtra postExtra;
  OscAuthor author;
  String pubDate = "";
  String company = "";
  String authorName = "";
  String title = "";
  String body = "";
  String commentContent = "";
  int comment = 0;
  bool favorite = false;
  int authorId = 0;
  int replyId = 0;
  List<String> tags;


  FocusNode focusNode = FocusNode();
  bool showKeyBord = false;

  @override
  void initState() {
    super.initState();

    httpRepository = HttpRepository();
    refresh();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    double bottomHeight = MediaQuery.of(context).viewInsets.bottom;
    if (bottomHeight > 50) {
      showKeyBord = true;
    } else {
      showKeyBord = false;
      FocusScope.of(context).requestFocus(FocusNode());
    }
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return CommonScaffold(
      bgColor: Colors.white,
        title: "详情",
        body: buildBody(),
    );
  }

  buildBody(){
    return Stack(
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            buildTitle(),
            buildAuthor(),
            buildContent(),
            ProjectCommentBarWidget(
                id: id,
                commentCount: comment,
                favorite: favorite,
                comment: commentContent,
                callback: ({
                  bool showInputWidget,
                  bool jump2CommentList,
                  bool reverseFavorite}){
                  if(showInputWidget){
                    setState(() {
                      showKeyBord = true;
                      focusNode.requestFocus();
                      FocusScope.of(context).requestFocus(focusNode);
                    });
                  } else if(jump2CommentList){
                    jumpToPageForResult(CommonPage(title: "评论列表", body: CommentList(id: id, type: type)));
                  } else if(reverseFavorite){
                    favoriteReverse();
                  }
                },
            ),
          ],
        ),
        Positioned(
          bottom: 0,
            child: Offstage(
              offstage: !showKeyBord,
              child: ProjectCommentInputWidget(
                content: commentContent,
                focusNode: focusNode,
                commentInputContentCallback: ({bool submit, String content}){
                  if(submit){
                    publishComment(content);
                    commentContent = "";
                    showKeyBord = false;
                    FocusScope.of(context).requestFocus(FocusNode());
                    setState(() {

                    });
                  } else {
                    commentContent = content;
                  }
                },
              ),
            )
        ),
      ],
    );
  }

  buildTitle(){
    List<TextSpan> textSpans = List<TextSpan>();
    textSpans.add(TextSpan(
      text: title,
      style: MyTextStyle.DETAIL_TITLE,
    ));
    if(!StringUtil.isEmpty(pubDate) && TimeUtil.isToday(pubDate)){
      textSpans.add(SmallWidgets.buildImageSpan(imageName: "ic_label_today", margin: EdgeInsets.only(right: Dimens.gap_view_smaller)));
    }
    if(tags != null){
      for(String tag in tags){
        textSpans.add(SmallWidgets.buildImageSpan(imageName: "ic_label_$tag", margin: EdgeInsets.only(right: Dimens.gap_view_smaller)));
      }
    }
    return Padding(
        padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
      child: RealRichText(
        textSpanList: textSpans,
      ),
    );
  }

  buildAuthor(){
    return Padding(
      padding: EdgeInsets.all(Dimens.gap_activity_horizontal),
      child: OscAuthorWidget(
        author: author,
        date: pubDate,
        showRelation: true,
        callback: (){
          if(author != null) {
            reverserRelation(id: authorId);
          }
        },
      ),
    );
  }


  buildContent(){
    return Expanded(
      child: Container(
        alignment: Alignment.center,
        child: StringUtil.isEmpty(body)?CircularProgressIndicator():buildWebView(),
      ),
    );
  }

  buildWebView(){
    return WebWidget(body: body,);
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  refresh() async{
    await loadMore();
  }


  loadMore() async{
    await httpRepository.getPostDetail(id: id, type: type).then((resp) {
      if (resp != null && resp.success) {
        detail = resp.result;
        if (detail != null) {
          title = detail.title;
          tags = detail.tags;
          postExtra = detail.extra;
          pubDate = detail.pubDate;

          comment = detail.statistics?.comment??0;
          favorite = detail.favorite;
          author = detail.author;
          if(author != null) {
            authorId = author.id;
            authorName = author.name;
          }
          body = detail.body;
        }
      }
    });
    if(mounted){
      setState(() {

      });
    }
  }

  favoriteReverse () async{
    await httpRepository.favoriteReverse(id: id, type: type).then((resp){
      OscFavoriteReverseResultEntity entity = resp.result;
      if(entity != null) {
        setState(() {
          favorite = entity.favorite;
        });
        showTips(favorite ? "收藏成功" : "取消收藏");
      }
    });
  }

  publishComment(String content) async{
    if(StringUtil.isEmpty(content)){
      showTips("请输入评论内容");
      FocusScope.of(context).requestFocus(focusNode);
      return;
    }
    await httpRepository.comment(id: id, replyId: replyId, type: type, content: content).then((resp) {
      showTips(resp.success? "评论成功" : "评论失败");
    });
  }

  Future<Null> reverserRelation({@required int id}) async{
    await httpRepository.reverseRelation(id: id).then((resp) {
      if(resp.success){
        int relation = resp.result.relation;
        author.relation = relation;
        showTips(relation==2?"关注成功":"取消关注");
      }
    });
    if (mounted) {
      setState(() {
      });
    }
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

}
